use serde_derive::{Serialize, Deserialize};
use rust_admin2_common::{models::{AdminRow as ModelRow, LoginInfo, LoginResult}, json::JsonPager,};
//use sqlx::{postgres::{PgRow}, row::Row,};
use sqlx::{postgres::{PgRow, PgQueryAs}, row::Row,};
use crate::common::{Pool, models::BackendModel};
use actix_web::{HttpRequest};
use anyhow::Result;

#[derive(Serialize, Deserialize, Debug)]
pub struct Admin;

impl BackendModel<ModelRow> for Admin {

    const TABLE_NAME: &'static str = "admins";
    const FIELDS: &'static str = "id, name, role_id, login_count, last_login, last_ip, status, created, updated, sort, remark";

    fn get_row_filter(r: &PgRow) -> ModelRow {
        unfold_fields!(r, {
            id => i32,
            name => String,
            login_count => i32,
            status => i16,
            remark => String,
            role_id => i32,
            sort => i32,
        }, {}, {created, last_login, updated,}, {}, {last_ip,})
    }


}

impl Admin {
    record_list!();

    /// 后台登录
    pub async fn login(req: &HttpRequest, db: &Pool, info: &LoginInfo) -> Result<LoginResult> {
        let ip = req.peer_addr().unwrap().ip(); //获取本次登录ip
        let ip_addr = ip.to_string();
        let sql = format!("SELECT admin_login('{}', '{}', '{}') AS message", info.username, info.password, ip_addr);
        let (message,): (String,) = sqlx::query_as(&sql)
            .fetch_one(db.get_ref())
            .await?;
        let mut code = 0u32;
        if &message != "ok" {
            code = 500;
        }
        Ok(LoginResult { code, message, })
    }

}
